<?php

namespace App\Http\Controllers\Admin;

use App\Model\Survey;
use App\Model\SurveyQuestion;
use App\Model\SurveyQuestionOption;
use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator;

class ApiController extends Controller
{
    /**
     * 添加问卷接口
     */
    public function addSurvey()
    {
        //接受参数
        $title = request('title');
        $intro = request('intro');
        $cate_id = request('cate_id');
        //新增问卷
        Survey::insert([
            'title' => $title,
            'intro' => $intro,
            'create_at' => time(),
            'cate_id' => $cate_id
        ]);
        return [
            'code' => 0,
            'msg' => '添加成功',
        ];
    }

    /**
     * 修改问卷接口
     */
    public function editSurvey()
    {
        try{
            $id = request('id');
            $title = request('title');
            $intro = request('intro');
            $cate_id = request('cate_id');

            Survey::where('id', $id)->update(['title' => $title, 'intro' => $intro, 'cate_id' => $cate_id]);
            return [
                'code' => 0,
                'msg' => '修改成功',
            ];
        }catch (\Exception $e){
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 为问卷调查添加提问的接口
     */
    public function addQuestion()
    {
        //接受参数
        $survey_id = request('survey_id');
        $title = request('title');
        $type = request('type');
        $options = request('options');

        //将问卷提问添加到对应的数据库并获取到对应的提问id(用作添加选项)
        $question_id = SurveyQuestion::insertGetId([
            'survey_id' => $survey_id,
            'title' => $title,
            'type' => $type,
        ]);

        //当type 为radio和checkbox 的时候需要向数据库添加选项
        if(in_array($type, ['radio', 'checkbox'])){
            //将options 的字符串拆分
            $options = preg_split('/\r\n/', $options);
            $options = array_map(function($e) use($question_id){
                return ['question_id' => $question_id, 'content' => trim($e)];
            }, $options);
            SurveyQuestionOption::insert($options);
        }

        return [
            'code' => 0,
            'msg' => '添加成功',
        ];
    }

    /**
     * 删除提问接口
     */
    public function deleteQuestion()
    {
        $id = request('id');    //得到提问的id, 删除该提问和提问下面的选项
        SurveyQuestion::destroy($id);   //删除提问
        SurveyQuestionOption::where('question_id', $id)->delete();  //删除提问的选项

        return [
            'code' => 0,
            'msg' => '删除成功',
        ];
    }

    /**
     * 删除问卷接口
     */
    public function deleteSurvey(){
        //需要删除问卷, 问卷的提问, 以及提问的选项
        $id = request('id');    //接收问卷的id
        $question_ids = SurveyQuestion::select('id')->where('survey_id', $id)->get()->toArray();
        if($question_ids){  //如果不为空则将对应的提问和选项删除
            $question_ids = array_map(function($e){
                return $e['id'];
            }, $question_ids);
            SurveyQuestionOption::whereIn('question_id', $question_ids)->delete();  //删除选项
            SurveyQuestion::destroy($question_ids); //删除提问
        }
        Survey::destroy($id);   //删除问卷
        return [
            'code' => 0,
            'msg' => '删除成功',
        ];
    }

    /**
     * 复制问卷调查接口
     */
    public function copySurvey()
    {
//        return request()->all();
        $id = request('id'); //要复制的问卷id
        $title = request('title'); //新问卷的名称

        $old_survey = Survey::find($id);
        //添加新的问卷
        $new_survey_id = Survey::insertGetId([
            'title' => $title,
            'intro' => $old_survey->intro,
            'create_at' => time(),
            'cate_id' => $old_survey->cate_id
        ]);

        //要先查出以前问卷拥有的提问和选项, 在把数据添加到新的问卷下
        $old_questions = SurveyQuestion::where('survey_id', $id)->get()->toArray();
        if($old_questions){ //有提问数据才有下面的操作
            $type = ['单选' => 'radio', '多选' => 'checkbox', '文本' => 'textarea'];
            $add_questions = array_map(function($a) use($new_survey_id, $type){
                $a['id'] = null;
                $a['survey_id'] = $new_survey_id;
                $a['type'] = $type[$a['type']];
                return $a;
            }, $old_questions);
            SurveyQuestion::insert($add_questions); //将提问添加到数据库
            //查询出新问题的数据
            $new_questions = SurveyQuestion::where('survey_id', $new_survey_id)->get()->toArray();

            //找到旧提问和新提问的对应关系
            $map = [];
            foreach($old_questions as $old_question){
                foreach ($new_questions as $new_question){
                    if($new_question['title'] == $old_question['title']){
                        $map[$old_question['id']] = $new_question['id'];
                    }
                }
            }

            //查询出旧问题的选项
            $old_question_ids = array_map(function($e){
                return $e['id'];
            }, $old_questions);
            $old_options = SurveyQuestionOption::whereIn('question_id', $old_question_ids)->get()->toArray();
            $add_options = array_map(function($e) use($map){
                $e['id'] = null;
                $e['question_id'] = $map[$e['question_id']];
                return $e;
            }, $old_options);
            //将选项添加到数据库
            SurveyQuestionOption::insert($add_options);
        }
        return [
            'code' => 0,
            'msg' => '复制成功'
        ];

    }

    /**
     * 添加员工接口
     */
    public function addStaff()
    {
        //laravel 的验证如果不想自动返回, 则使用Validator的make 方法
        $validator = Validator::make(request()->all(), [
            'name' => 'required|unique:users',
            'email' => 'unique:users',
            'password' => 'required|min:6|confirmed',
            'realname' => 'required',
            'dpt_id' => 'required',
        ]);
        if($validator->fails()){
            return [
                'code' => 1,
                'msg' => $validator->errors()->first(),
            ];
        }
        //接受参数
        $name = request('name');
        $email = request('email');
        $password = request('password');
        $realname = request('realname');
        $dpt_id = request('dpt_id');
        User::create([
            'name' => $name,
            'email' => $email,
            'password' => bcrypt($password),
            'realname' => $realname,
            'dpt_id' => $dpt_id,
        ]);
        return [
            'code' => 0,
            'msg' => '创建成功',
        ];
    }

    /**
     * 重置密码接口
     */
    public function resetPassword()
    {
        //laravel 的验证如果不想自动返回, 则使用Validator的make 方法
        $validator = Validator::make(request()->all(), [
            'id' => 'required',
            'password' => 'required|min:6|confirmed',
        ]);
        if($validator->fails()){
            return [
                'code' => 1,
                'msg' => $validator->errors()->first(),
            ];
        }

        $id = request('id'); //用户id
        $password = request('password'); //新密码

        User::where('id', $id)->update(['password' => bcrypt($password)]);

        return [
            'code' => 0,
            'msg' => '重置成功',
        ];
    }

    /**
     * 删除用户接口
     */
    public function deleteUser()
    {
        $id = request('id');
        User::destroy($id);
        return [
            'code' => 0,
            'msg' => '删除成功',
        ];
    }

    /**
     * 获取用户信息接口
     */
    public function getUserInfo()
    {
        $id = request('id');
        return User::find($id);
    }

    /**
     * 编辑用户信息接口
     */
    public function editUserInfo(){
        //laravel 的验证如果不想自动返回, 则使用Validator的make 方法
        $validator = Validator::make(request()->all(), [
            'id' => 'required',
            'realname' => 'required',
            'dpt_id' => 'required'
        ]);
        if($validator->fails()){
            return [
                'code' => 1,
                'msg' => $validator->errors()->first(),
            ];
        }
        $id = request('id');
        $email = request('email');
        $realname = request('realname');
        $dpt_id = request('dpt_id');

        $user = User::find($id);
        $user->email = $email;
        $user->realname = $realname;
        $user->dpt_id = $dpt_id;
        $user->save();

        return [
            'code' => 0,
            'msg' => '修改成功',
        ];
    }
}
